# -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 09:15:36 2019

@author: leslie lee
"""
from PIL import Image
import tensorflow as tf
import numpy as np
import mnist_forward
import mnist_backward

def application():
    testNum = int(input("input the number of test pictures:"))
    for i in range(testNum):
        testPic = input("the path of test picture:")
        testPicArr = pre_pic(testPic)
        preValue = restore_model(testPicArr)
        print("The prediction number is:", preValue)

def restore_model(testPicArr):
     with tf.Graph().as_default() as g:
        x=tf.placeholder(tf.float32,[None,mnist_forward.input_node])
        y=mnist_forward.forward(x,None)
        preValue=tf.argmax(y,1)
        
        ema = tf.train.ExponentialMovingAverage(mnist_backward.moving_average_decay)
        ema_restore=ema.variables_to_restore()
        saver=tf.train.Saver(ema_restore)
        
        with tf.Session() as sess:
                ckpt = tf.train.get_checkpoint_state(mnist_backward.model_save_path) 
                if ckpt and ckpt.model_checkpoint_path:  
                    saver.restore(sess, ckpt.model_checkpoint_path)
                    
                    preValue=sess.run(preValue,feed_dict={x:testPicArr})
                    return preValue
                else:
                    print("have no checkpoint file")
                    return -1

def pre_pic(picName):
    img=Image.open(picName)
    reIm=img.resize((28,28),Image.ANTIALIAS)
    im_arr=np.array(reIm.convert('L'))  #转灰度矩阵
    threshold=50
    for i in range(28):
        for j in range(28):
            im_arr[i][j]=255-im_arr[i][j]
            if (im_arr[i][j]<threshold):
                im_arr[i][j]=0
            else:
                im_arr[i][j]=255
                
    nm_arr=im_arr.reshape([1,784])
    nm_arr=nm_arr.astype(np.float32)
    img_ready=np.multiply(nm_arr,1.0/255.0)
    
    return img_ready

    

if __name__ == '__main__':
    application()